package com.liycloud.common.web.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liycloud.common.core.util.ResultVo;

import com.baomidou.mybatisplus.extension.service.IService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.Serializable;


/**
 * 基础Controller, 实现基本的CRUD
 *
 * @param <BizService> 业务Service
 * @param <T> 返回的 模型对象
 */
public class BaseController<BizService extends IService<T>,  T extends Serializable> {


	@Autowired
	private BizService bizService;

	public BaseController() {
	}

	/**
	 * 新增单条记录
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = { "/add" }, method = { RequestMethod.POST })
	@ResponseBody
	public ResultVo add(@RequestBody @Valid T entity) {
		try {
			bizService.save(entity);
			return ResultVo.ok(entity,"新增成功");
		}
		catch (Exception e) {
			return ResultVo.failed(entity,"新增失败: " + e.getMessage());
		}
	}

	/**
	 * 根据 主键ID 删除
	 * @param id
	 * @return
	 */
	@RequestMapping(value = { "/del/{id}"}, method = { RequestMethod.DELETE, RequestMethod.GET })
	@ResponseBody
	public ResultVo removeById(@PathVariable("id")  String id) {
		try {
			bizService.removeById(id);
			return ResultVo.ok("根据主键ID删除成功");
		}
		catch (Exception e) {
			return ResultVo.failed("根据主键ID删除失败: " + e.getMessage());
		}
	}


	/**
	 * 根据 ID 选择更新
	 *
	 * @param entity 实体对象
	 */
	@RequestMapping(value = { "/update" }, method = { RequestMethod.PUT, RequestMethod.POST })
	@ResponseBody
	public ResultVo update(@RequestBody final T entity) {
		try {
			bizService.updateById(entity);
			return ResultVo.ok(entity,"根据ID更新成功");
		}
		catch (Exception e) {
			return ResultVo.failed("根据ID更新失败: " + e.getMessage());
		}
	}

	/**
	 * 单条查询 根据主键ID 单条查询
	 * @param id
	 */
	@RequestMapping(value = {"/get/{id}"},  method = {RequestMethod.GET})
	@ResponseBody
	public ResultVo get(@PathVariable("id") String id) {

		try {
			T byId = bizService.getById(id);
			return ResultVo.ok(byId);
		} catch (Exception e) {
			return ResultVo.failed("单条查询失败: " + e.getMessage());
		}
	}


	/**
	 * 分页查询
	 * @param page 参数集
	 * @param entity 查询参数列表
	 * @return 用户集合
	 */
	@GetMapping("/page")
	@ResponseBody
	public ResultVo getUserPage(Page page, T entity) {
		try {
			// 条件查询实体类封装
			Wrapper<T> queryWrapper = new Wrapper<T>() {
				@Override
				public T getEntity() {
					return entity;
				}

				@Override
				public MergeSegments getExpression() {
					return null;
				}

				@Override
				public void clear() {

				}

				@Override
				public String getSqlSegment() {
					return null;
				}
			};
			Page pageResult = bizService.page(page, queryWrapper);
			return ResultVo.ok(pageResult);
		} catch (Exception e) {
			return ResultVo.failed("分页查询失败: " + e.getMessage());
		}
	}




}
